package orders

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CancelOrderByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCancelOrderByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CancelOrderByIdApiLogic {
	hostname, _ := os.Hostname()
	return &CancelOrderByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CancelOrderByIdApiLogic) CancelOrderByIdApi(req *types.CancelReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	ordersEntity, err := service.OrdersService.GetByIdApi(l.ctx, req.ID)
	if errors.Is(err, gorm.ErrRecordNotFound) || ordersEntity.EnterpriseID != accountInfo.EnterpriseId {
		return "", errors.New("传递的主键错误")
	}
	if ordersEntity.Status != enum.OrdersCreateEnum {
		return "", errors.New("当前订单状态不支持退货")
	}

	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	if err = service.OrdersService.ModifyStatusByIdApi(l.ctx, tx, []int64{req.ID}, enum.OrdersCancelEnum); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("取消订单失败")
	}

	// 取消采购计划
	//ordersDetailEntity, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{req.ID})
	ordersDetailEntity, err := service.OrdersSpuService.GetListByOrdersIDApi(l.ctx, req.ID)
	if err == nil && len(ordersDetailEntity) > 0 {
		for _, item := range ordersDetailEntity {
			if item.PurchaseStatus != enum.OrdersSpuPurchaseStatusWait {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("订单状态未处于待采购状态，无法取消")
			}
			updates := map[string]any{
				"purchase_status": enum.OrdersSpuPurchaseStatusCanceled,
			}
			if err = service.OrdersSpuService.ModifyByIDApi(l.ctx, tx, item.ID, updates); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("退货失败")
			}
			// 采购计划和订单的关系
			//planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailIdApi(l.ctx, item.ID)
			planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersSpuIDApi(l.ctx, item.ID)
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				purchasePlanEntity, err := service.PurchasePlanService.GetByIdApi(l.ctx, planOrdersEntities.PurchasePlanID)
				if !errors.Is(err, gorm.ErrRecordNotFound) {
					if item.RequireCount.Equal(purchasePlanEntity.RequirementsCount) {
						if err = service.PurchasePlanService.ModifyStatusByIdListApi(l.ctx, tx, []int64{planOrdersEntities.PurchasePlanID}, 30); err != nil {
							if err = tx.Rollback(); err != nil {
								return "", err
							}
							return "", errors.New("退货失败")
						}
					} else {
						// 减少采购计划数量
						if err = service.PurchasePlanService.ModifyRequirementsCountByIdApi(l.ctx, tx, planOrdersEntities.PurchasePlanID, purchasePlanEntity.RequirementsCount.Sub(item.RequireCount)); err != nil {
							if err = tx.Rollback(); err != nil {
								return "", err
							}
							return "", errors.New("退货失败")
						}
					}
				}
			}
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("退货失败")
	}
	return "操作成功", nil
}
